package net.godbirds.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * HTTP请求工具类
 * @author Darker.Wang
 * @version NET.GODBIRDS 1.0
 * @date 2018-09-24
 *
 */
public class HttpUtils{
	private static RequestConfig config ;
	private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
	private static int connectTimeout = 60000;
	private static int connectRequestTimeout = 60000;
	private static int socketTimeout = 60000;
	private static boolean redirectsEnabled = true;
	/**
	 * 连接超时
	 * @return
	 */
	public static int getConnectTimeout() {
		return connectTimeout;
	}
	/**
	 * 连接超时
	 * @param connectTimeout
	 */
	public static void setConnectTimeout(int connectTimeout) {
		HttpUtils.connectTimeout = connectTimeout;
	}
	/**
	 * 请求超时
	 * @return
	 */
	public static int getConnectRequestTimeout() {
		return connectRequestTimeout;
	}
	/**
	 * 请求超时
	 * @param connectRequestTimeout
	 */
	public static void setConnectRequestTimeout(int connectRequestTimeout) {
		HttpUtils.connectRequestTimeout = connectRequestTimeout;
	}
	/**
	 * Socket超时
	 * @return
	 */
	public static int getSocketTimeout() {
		return socketTimeout;
	}
	/**
	 * Socket超时
	 * @param socketTimeout
	 */
	public static void setSocketTimeout(int socketTimeout) {
		HttpUtils.socketTimeout = socketTimeout;
	}
	/**
	 * 是否允许重定向
	 * @return
	 */
	public static boolean isRedirectsEnabled() {
		return redirectsEnabled;
	}
	/**
	 * 是否允许重定向
	 * @param redirectsEnabled
	 */
	public static void setRedirectsEnabled(boolean redirectsEnabled) {
		HttpUtils.redirectsEnabled = redirectsEnabled;
	}
	/**
	 * 获取默认请求设置
	 * @return
	 */
	public static RequestConfig getRequestConfig() {
		if(config == null) {
			config = RequestConfig.custom()
	                .setConnectTimeout(connectTimeout)   //设置连接超时时间
	                .setConnectionRequestTimeout(connectRequestTimeout) // 设置请求超时时间
	                .setSocketTimeout(socketTimeout)
	                .setRedirectsEnabled(redirectsEnabled)//默认允许自动重定向
	                .build();
		}
		return config;
	}
	/**
	 * 通用GET请求
	 * @param url
	 * @return
	 */
	public static String doGet(String url) {
		CloseableHttpClient httpCilent = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(getRequestConfig());
		String rtvStr = null;
		try {
			logger.info(">>> doGet: "+url);
            HttpResponse httpResponse = httpCilent.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == 200){
            	rtvStr = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
            }else if(httpResponse.getStatusLine().getStatusCode() == 400){
                //TODO SOMETHING
            }else if(httpResponse.getStatusLine().getStatusCode() == 500){
                //TODO SOMETHING
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpCilent.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return rtvStr;
	}
	
	/**
	 * 通用POST请求，参数为MAP
	 * @param url
	 * @param paramsMap
	 * @return
	 */
	public static String doPost(String url, Map<String, Object> paramsMap){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
                .setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
        httpPost.setConfig(requestConfig);
         
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : paramsMap.keySet()) {
            nvps.add(new BasicNameValuePair(key, String.valueOf(paramsMap.get(key))));
        }
        try {
        	logger.info(">>> doGet: "+url);
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            String rtvStr = null;
            if (response.getStatusLine().getStatusCode() == 200) {
            	rtvStr = EntityUtils.toString(response.getEntity());
                 return rtvStr;
            } else {
                return "Error Response: " + response.getStatusLine().toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "post failure :caused by-->" + e.getMessage().toString();
        }finally {
            if(null != httpClient){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	/**
	 * 通用POST请求，参数为JSON
	 * @param url
	 * @param jsonParams
	 * @return
	 */
	public static String doPostForJson(String url, String jsonParams){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(getRequestConfig());
        httpPost.setHeader("Content-Type","application/json");
        try {
        	logger.info(">>> doGet: "+url);
            httpPost.setEntity(new StringEntity(jsonParams,ContentType.create("application/json", "utf-8")));
            HttpResponse response = httpClient.execute(httpPost);
            logger.info(">>> "+response.getStatusLine().getStatusCode());
            logger.info(">>> "+response.getStatusLine().toString());
            return String.valueOf(response.getStatusLine().getStatusCode());
        } catch (Exception e) {
            e.printStackTrace();
            return "post failure :caused by-->" + e.getMessage().toString();
        }finally {
            if(null != httpClient){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
}
}
